<?php

namespace plugin\muadmin\app\admin\controller;

use plugin\muadmin\app\common\base\BaseAdminController;
use plugin\muadmin\app\common\core\DbHand;
use think\facade\Db;
use think\Validate;

class Install extends BaseAdminController
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $noHasModel = ['*'];
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 检查扩展
     * @return \support\Response
     */
    public function check()
    {
        $dir = base_path().'/plugin/';
        $not = checkDirPermissions($dir);
        $res = [
            [
                'name'=>'php_version',
                'title'=>'php版本',
                'value'=>phpversion(),
                'status'=>phpversion()>=8.1?'success':'error',
//                'status'=>'error',
                'desc'=>'最低8.1'
            ],
            [
                'name'=>'plugin_is_write',
                'title'=>'插件目录可写',
                'value'=>(in_array($dir, $not['not_writable'])||in_array($dir, $not['unreadable']))?'否':'是',
                'status'=>(in_array($dir, $not['not_writable'])||in_array($dir, $not['unreadable']))?'error':'success',
                'desc'=>'plugin必须可读可写'
            ],
            [
               'name'=>'webman/think-orm' ,
                'title'=>'think-orm扩展',
                'value'=>class_exists('think\facade\Db')?'已安装':'未安装',
                'status'=>class_exists('think\facade\Db')?'success':'error',
                'desc'=>'think-orm扩展必须安装'
            ],
            [
                'name'=>'webman/think-cache' ,
                'title'=>'think-cache扩展',
                'value'=>class_exists('support\think\Cache')?'已安装':'未安装',
                'status'=>class_exists('support\think\Cache')?'success':'error',
                'desc'=>'think-cache扩展必须安装'
            ],
            [
                'name'=>'webman/console' ,
                'title'=>'console扩展',
                'value'=>class_exists('Webman\Console\Command')?'已安装':'未安装',
                'status'=>class_exists('Webman\Console\Command')?'success':'error',
                'desc'=>'console扩展必须安装'
            ],
            [
                'name'=>'redis' ,
                'title'=>'redis扩展',
                'value'=>extension_loaded('redis')?'已安装':'未安装',
                'status'=>extension_loaded('redis')?'success':'error',
                'desc'=>'redis扩展必须安装'
            ],
            [
                'name'=>'webman/redis-queue' ,
                'title'=>'redis-queue扩展',
                'value'=>class_exists('Webman\RedisQueue\Redis')?'已安装':'未安装',
                'status'=>class_exists('Webman\RedisQueue\Redis')?'success':'error',
                'desc'=>'redis-queue扩展必须安装'
            ],
            [
                'name'=>'topthink/think-template' ,
                'title'=>'topthink/think-template扩展',
                'value'=>class_exists('support\view\ThinkPHP')?'已安装':'未安装',
                'status'=>class_exists('support\view\ThinkPHP')?'success':'error',
                'desc'=>'redis-cluster扩展必须安装'
            ],
            [
                'name'=>'webman/event',
                'title'=>'webman/event扩展',
                'value'=>class_exists('Webman\Event\Event')?'已安装':'未安装',
                'status'=>class_exists('Webman\Event\Event')?'success':'error',
                'desc'=>'webman/event扩展必须安装'
            ],
            [
                'name'=>'vlucas/phpdotenv',
                'title'=>'vlucas/phpdotenv扩展',
                'value'=>class_exists('Dotenv\Dotenv')?'已安装':'未安装',
                'status'=>class_exists('Dotenv\Dotenv')?'success':'error',
                'desc'=>'vlucas/phpdotenv扩展必须安装'
            ]
        ];
        return  $this->success('success',$res);
    }
    public function link_data()
    {
        $data = $this->request->all();
        if(empty($data['type'])){
            return $this->error('请选择数据库类型');
        }
        if($data['type']=='mysql'){
            $rule = [
                'type|数据库类型'=>'require',
                'hostname|数据库地址'=>'require',
                'hostport|数据库端口'=>'require',
                'username|数据库用户名'=>'require',
                'password|数据库密码'=>'require',
                'charset|数据库编码'=>'require',
            ];
        }elseif ($data['type']=='sqlite'){
            $rule = [
                'type|数据库类型'=>'require',
                'database|数据库地址'=>'require',
//                'hostport|数据库端口'=>'require',
//                'username|数据库用户名'=>'require',
//                'password|数据库密码'=>'require',
//                'charset|数据库编码'=>'require',
            ];
        }
        $validate = (new Validate());
        $validate->rule($rule);
        $res = $validate->check($data);
        if($res===false){
            return $this->error($validate->getError());
        }
        if($data['type']=='sqlite'){
            $res = DbHand::instance()->has_sqlit_db($data['type'],$data['database']);
            if($res){
                return $this->success(DbHand::instance()->getError());
            }
            return $this->success('数据库连接成功');
        }
        $res = DbHand::instance()->has_db($data['type'],$data['hostname'],$data['hostport'],$data['username'],$data['password'],$data['charset']);
//        var_dump($res);
        if($res){
            return $this->success(DbHand::instance()->getError());
        }
        return $this->error(DbHand::instance()->getError());
    }

    /**
     * 创建数据库
     * @return \support\Response
     */
    public function install_sql()
    {
        $row = $this->request->all();
        $data = $row['row'];
        $obj = DbHand::instance();
        if($data['type']=='sqlite'){
            $res = $obj->has_sqlit_db($data['type'],$data['database']);
        }elseif ($data['type']=='mysql'){
            $res = $obj->has_db($data['type'],$data['hostname'],$data['hostport'],$data['username'],$data['password'],$data['charset']);
        }
        if($res===false){
            return $this->error($obj->getError());
        }
        clearstatcache();
        if($data['type']=='sqlite'){
            $sqlPath = base_path()."/plugin/muadmin/data/install.sqlite.sql";
        }elseif ($data['type']=='mysql'){
            $sqlPath = base_path()."/plugin/muadmin/data/install.sql";
        }

        try {
            $obj->change_database($data['database'],$data['charset']);
            if(is_file($sqlPath)){
                $obj->update_sql($sqlPath,$data['prefix']);
            }
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
        clearstatcache();
        $database_config_file = base_path() . "/plugin/{$this->request->plugin}/config/database.php";

        $config_content = <<<EOF
<?php
return  [
    'default' => '{$data['type']}',
    'connections' => [
        'mysql' => [
            'driver'      => '{$data['type']}',
            'host'        => '{$data['hostname']}',
            'port'        => '{$data['hostport']}',
            'database'    => '{$data['database']}',
            'username'    => '{$data['username']}',
            'password'    => '{$data['password']}',
            'charset'     => '{$data['charset']}',
            'collation'   => 'utf8mb4_general_ci',
            'prefix'      => '{$data['prefix']}',
            'strict'      => true,
            'engine'      => null,
        ],
        'sqlite' => [
            'driver' => 'sqlite',
            'database' => base_path('webman_demo.db'),
            'prefix' => '{$data['prefix']}'
        ],
    ],
];
EOF;
        file_put_contents($database_config_file, $config_content);
        $thinkorm = <<<EOT
<?php

return [
    'default' => '{$data['type']}',
    'connections' => [
        '{$data['type']}' => [
            // 数据库类型
            'type' => '{$data['type']}',
            // 服务器地址
            'hostname' => '{$data['hostname']}',
            // 数据库名
            'database' => '{$data['database']}',
            // 数据库用户名
            'username' => '{$data['username']}',
            // 数据库密码
            'password' => '{$data['password']}',
            // 数据库连接端口
            'hostport' => '{$data['hostport']}',
            // 数据库连接参数
            'params' => [
                // 连接超时3秒
                \PDO::ATTR_TIMEOUT => 3,
            ],
            // 数据库编码默认采用utf8
            'charset' => '{$data['charset']}',
            // 数据库表前缀
            'prefix' => '{$data['prefix']}',
            // 断线重连
            'break_reconnect' => {$data['break_reconnect']},
            // 自定义分页类
            'bootstrap' =>  '',
            // 连接池配置
            'pool' => [
                'max_connections' => 5, // 最大连接数
                'min_connections' => 1, // 最小连接数
                'wait_timeout' => 3,    // 从连接池获取连接等待超时时间
                'idle_timeout' => 60,   // 连接最大空闲时间，超过该时间会被回收
                'heartbeat_interval' => 50, // 心跳检测间隔，需要小于60秒
            ],
        ],
    ],
];

EOT;
        $config_dir = base_path()."/plugin/{$this->request->plugin}/config/";
        if(!is_dir($config_dir)){
            mkdir($config_dir, 0777, true);
        }
        file_put_contents($config_dir.'think-orm.php', $thinkorm);

        $dir_config = base_path()."/config/think-orm.php";
        file_put_contents($dir_config, $thinkorm);

        $file = base_path()."/plugin/{$this->request->plugin}/config/install.lock";
        if(!is_file($file)){
            file_put_contents($file, '1');
        }
        if (function_exists('posix_kill')) {
            set_error_handler(function () {});
            posix_kill(posix_getppid(), SIGUSR1);
            restore_error_handler();
        }
        clearstatcache();
        reloadWebman();
        return $this->success('数据库安装成功');
    }

    public function update_admin()
    {
        $data = $this->request->all();
        if(!empty($data['username'])&&!empty($data['password'])){
            $salt = random_str(4);
            $update = [
                'username' => $data['username'],
                'password' => create_password($data['password'], $salt),
                'salt' => $salt,
            ];
            Db::name('admin')->where('id',1)->update($update);
            Db::name('config')->where('name','name')->update(['value'=>$data['site_name']]);
            return $this->success('更新成功');
        }
        return $this->success('更新成功', $data);
    }

}